const { resolve, extname } = require('path')
const { readdirSync } = require('fs')
const Hwp = require('html-webpack-plugin')

const titles = {
    all: "某某网站",
    login: "请登录",
    register: "请注册"
}

const config = {
    devtool: 'inline-source-map',
    entry: {},
    output: {
        path: resolve('./dist'),
        filename: '[name].js'
    },
    plugins: [],
    resolve: {
        alias: {
            '@': resolve('./src')
        }
    },
    module: {
        rules: [
            // 配置 css
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
            // 配置 less
            {
                test: /\.less$/,
                use: ['style-loader', 'css-loader', 'less-loader']
            },
            // 配置 html
            {
                test: /\.html$/,
                use: ['html-loader']
            },
            // 配置 pug
            {
                test: /\.pug$/,
                use: ['pug-loader']
            },
            // 配置图片
            {
                test: /\.(png|jpg|gif|jpeg)$/,
                type: "asset",
                generator: {
                    filename: "img/[name].[hash:6][ext]"
                }
            },
            // 配置 babel
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } }
            },
        ]
    }
}

const entryFiles = readdirSync(resolve('./src'))
for (let file of entryFiles) {
    const ext = extname(file)
    if (ext === '.js') {
        const name = file.replace(ext, '')
        config.entry[name] = resolve('./src', file)
        config.plugins.push(new Hwp({
            filename: `${name}.html`,
            chunks: [name],
            title: titles[name] || titles['all'],
        }))
    }
}

module.exports = config